package dao

import (
	"fmt"
	"lib/structs/ams"
	"lib/structs/tables"
)

var PolicyDao = new(policyDao)

type policyDao struct {
}

func (d policyDao) Delete(id int64) (err error) {
	err = DB.Delete(&tables.AmsPolicy{Id: id}).Error
	return
}

func (d policyDao) Update(m tables.AmsPolicy) (err error) {
	if m.Id == 0 {
		err = fmt.Errorf("update id is not empty")
		return
	}
	err = DB.Save(&m).Error
	return
}

func (d policyDao) FindById(id int64) (m tables.AmsPolicy, err error) {
	err = DB.Where("id=?", id).Find(&m).Error
	return
}

func (d policyDao) FindListByName(in ams.SearchPolicyDto) (li []tables.AmsPolicy, err error) {
	tx := DB.Model(&tables.AmsPolicy{})
	if in.Name != "" {
		tx.Where("name like ?", fmt.Sprintf("%%%s%%", in.Name))
	}
	if in.ResCode != "" {
		tx.Where("res_code = ?", in.ResCode)
	}
	err = tx.Find(&li).Error
	return
}

func (d policyDao) Create(m *tables.AmsPolicy) error {
	err := DB.Create(m).Error
	return err
}

func (d policyDao) FindList() (li []tables.AmsPolicy, err error) {
	err = DB.Model(&tables.AmsPolicy{}).Find(&li).Error
	return
}
